package com.wpx.log.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.DateTime;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONValidator;
import com.wpx.log.core.module.Entry;

public class Utils {

	/**
	 * 	获取类的成员的属性
	 */
	public static  Field[] getMemberField(Class<?> clazz) {
		Field[] fs = clazz.getDeclaredFields();
		if(fs == null) {
			fs = new Field[0];
		}
		
		clazz = clazz.getSuperclass();
		if(clazz != null) {
			fs = IgnoreField(fs, getMemberField(clazz));
		}

		return Arrays.stream(fs).filter(f -> !Modifier.isStatic(f.getModifiers())).toArray(Field[]::new); 
	}

	/**
	 * 合并数组
	 */
	public static <T> T[] arrayMerge(T[] t1, T[] t2) {
		t1 = Arrays.copyOf(t1, t1.length + t2.length);		
		System.arraycopy(t2, 0, t1, t1.length-t2.length, t2.length);
		return t1;
	}
	
	/**
	 * 合并f2到 f1,忽略掉类型名称相同的
	 */
	public static Field[] IgnoreField(Field[] fs1, Field[] fs2) {
		fs2 = Arrays.stream(fs2).filter(f -> {
			for (int i = 0; i < fs1.length; i++) {
				Field f1 = fs1[i];
				if(f1.getType() == f.getType() && f.getName().equals(f1.getName())) {
					return false;
				}
			}
			return true;
		}).toArray(Field[]::new);
		
		return arrayMerge(fs1, fs2);
	}
	
//	
//	
//	public static void main(String[] args) {
//		Integer[] a1 = {1,2,3,4};
//		Integer[] a2 = {5,6,7,8,9};
//		Integer[] a3 = arrayMerge(a1, a2);
//		System.out.println(Arrays.toString(a3));
//	}
//	
//	
	

	/**
	 * 	获取异常的栈信息
	 */
	public static String getStackTrace(Throwable e) {
		String msg = "";
		StringWriter stringWriter = new StringWriter();
		try(PrintWriter printWriter= new PrintWriter(stringWriter);){
			e.printStackTrace(printWriter);
			msg = stringWriter.toString();
		}
		return msg;
	}

	/**
	 * 时间格式化
	 */
	public static String dateFormat(Date date, String pattern) {
		DateTime jdate = new DateTime(date.getTime());
		return jdate.toString(pattern);
	}


	/**
	 * 
	 */
	public static Object getValue(EvaluationContext context, String expressionString, boolean isBeanFactory) {
		return getValue(context, expressionString, isBeanFactory, Object.class);
	}

	public static <T> T getValue(EvaluationContext context, String expressionString, boolean isBeanFactory, Class<T> desiredResultType) {
		ExpressionParser parser = new SpelExpressionParser();
		Expression expression = null;
		if(isBeanFactory) {
			expression = parser.parseExpression(expressionString);
		}else {
			expression = parser.parseExpression(expressionString, new TemplateParserContext("${", "}"));
		}
		return expression.getValue(context, desiredResultType);
	}	


	public static String getRequestIp(HttpServletRequest request) {
		String ip = "";

		//X-Forwarded-For：Squid 服务代理
		String ipAddresses = request.getHeader("X-Forwarded-For");

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//Proxy-Client-IP：apache 服务代理
			ipAddresses = request.getHeader("Proxy-Client-IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//WL-Proxy-Client-IP：weblogic 服务代理
			ipAddresses = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//HTTP_CLIENT_IP：有些代理服务器
			ipAddresses = request.getHeader("HTTP_CLIENT_IP");
		}

		if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			//X-Real-IP：nginx服务代理
			ipAddresses = request.getHeader("X-Real-IP");
		}

		//有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
		if (ipAddresses != null && ipAddresses.length() != 0) {
			ip = ipAddresses.split(",")[0];
		}

		//还是不能获取到，最后再通过request.getRemoteAddr();获取
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}


	/**
	 * 检查ip合法性
	 */
	public static boolean checkIp(String ip) {
		if(StringUtils.isEmpty(ip)) {
			return false;
		}

		String[] split = ip.split("\\.");
		if(split.length != 4) {
			return false;
		}

		for (String numStr : split) {
			try {
				int num = Integer.parseInt(numStr);
				if(num < 0 | num > 255) {
					return false;
				}
			} catch (Exception e) {
				return false;
			}
		}

		return true;
	}

	
	public static boolean isJson(String str) {
		if(StringUtils.isEmpty(str)) {
			return false;
		}
		str = str.trim();
		if(str.length() == 0) {
			return false;
		}
		char c = str.trim().charAt(0);
		if(c != '[' && c != '{') {
			return false;
		}
		try {
			return JSONValidator.from(str).validate();
		} catch (Exception e) {
			
		}
		
		return false;
	}
	
	public static void main(String[] args) {
		System.out.println(isJson("2"));
	}
}
